Unity的Inspector使用[Serialization Field]
或是宣告Public 變量的時候
會根據變量的類型顯示簡易的操控面板
但如果你想要更複雜的功能(像是加按鈕,表單)
就需要自己自定義Inspector
創建MonoBehavior腳本:
using UnityEngine;
public class MyCustomComponent : MonoBehaviour
{
public string playerName;
public int playerScore;
}
創建Editor腳本:
在Assets/Editor
文件夾中創建一個新的C#腳本(如果沒有Editor文件夾,請創建一個)。
這個腳本將用來自定義Inspector:
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MyCustomComponent))]
public class MyCustomComponentEditor : Editor
{
public override void OnInspectorGUI()
{
MyCustomComponent myComponent = (MyCustomComponent)target;
myComponent.playerName = EditorGUILayout.TextField("Player Name", myComponent.playerName);
myComponent.playerScore = EditorGUILayout.IntField("Player Score", myComponent.playerScore);
if (GUILayout.Button("Reset Score"))
{
myComponent.playerScore = 0;
}
string[] options = new string[] { "Option 1", "Option 2", "Option 3" };
int index = EditorGUILayout.Popup("Options", 0, options);
// 確保在Inspector中任何更改都能被保存
if (GUI.changed)
{
EditorUtility.SetDirty(myComponent);
}
}
}
GUILayout.Button
方法來創建一個按鈕。當按鈕被點擊時,可以執行特定的操作。EditorGUILayout.Popup
方法來創建一個下拉選單,讓用戶從多個選項中選擇。除了自定義Inspector,你還可以擴展Unity的Menu和WindowPanel。
Menu:你可以在Unity的菜單中添加自定義選項。
public class MyMenuItems
{
[MenuItem("MyMenu/Do Something")]
private static void DoSomething()
{
Debug.Log("Doing something...");
}
}
WindowPanel:創建自定義的編輯器窗口。
public class MyWindow : EditorWindow
{
[MenuItem("Window/My Window")]
public static void ShowWindow()
{
GetWindow<MyWindow>("My Window");
}
private void OnGUI()
{
GUILayout.Label("This is a custom editor window", EditorStyles.boldLabel);
}
}
通過自定義Inspector、添加按鈕和下拉選單,以及擴展Menu和WindowPanel
可以大大提高Unity Editor的可用性和功能性。